package com.gitee.stream;

import org.junit.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * 流的创建方式
 *
 * @author gcq
 * @Create 2022-07-02
 */
public class StreamConstructor {

    /**
     * 基于 Stream.of 创建流
     */
    @Test
    public void streamFormValue() {
        Stream integerStream = Stream.of(1, 2, 3, 4, 5);
        integerStream.forEach(System.out::println);
    }

    /**
     * 基于数组创建流
     */
    @Test
    public void streamFormArray() {
        int[] numbers = {1, 2, 3, 4, 5};

        IntStream stream = Arrays.stream(numbers);
        stream.forEach(System.out::println);
    }

    /**
     * 基于文件创建流
     *
     * @throws IOException
     */
    @Test
    public void streamFromFile() throws IOException {
        Stream<String> lines = Files.lines(Paths.get("D:\\workspace\\gitee\\idea_projects\\996\\" +
                "stream\\src\\test\\java\\com\\gitee\\stream\\StreamConstructor.java"));
        lines.forEach(System.out::println);
    }

    /**
     * 通过函数生成流（无限流）
     */
    @Test
    public void streamFormFunction() {
        Stream<Integer> iterate = Stream.iterate(0, n -> n + 2);
//        iterate.forEach(System.out::println);
        Stream<Double> generate = Stream.generate(Math::random);
        generate.limit(100).forEach(System.out::println);
    }
}